<template>
  <el-card v-loading="loading" class="m-2 user-add">
    <avue-form v-model="form" :option="option" @submit="handleSubmit" />
  </el-card>
</template>

<script setup lang="ts">
import userEditOption from "./avue-options";
import router from "@/router";
import { UserModel } from "@/model/user-model";
import UserAPI from "@/api/user";

defineOptions({
  name: "UserEdit",
});

const route = useRoute();
const loading = ref(false);
const form = ref<UserModel>({
  // mobile: "13320098527",
  // name: "chen",
  // sex: "男",
  // domiciles: ["江西省", "萍乡市", "安源区"],
  // id_card: "430682199909091111",
  // birthday: "1999-09-09",
  // address_citys: ["江西省", "萍乡市", "安源区"],
  // address_detail: "113.825882,27.647687,江西省萍乡市安源区青山镇城西公交客运站(水口)(公交站)",
  // family_situation: "12312312",
  // house_situation: "自有",
  // family_number: 1,
  // elderly_number: 1,
  // family_contact: "chen",
  // family_contact_phone: "13320098527",
  // identity_characteristics: "分散供养特困老年人家庭",
  // project_items: ["防滑处理", "高差处理"],
  // project_other: "其他内容",
  // street_result: 1,
  // civil_result: 1,
});

const option = ref(userEditOption);

// 监听userId变化，重新获取数据
watch(
  () => route.query,
  async () => fetchData(),
  {
    immediate: true,
    deep: true,
  }
);

/**
 * @description 获取数据
 */
function fetchData() {
  const userId = route.query.id;
  loading.value = true;
  UserAPI.detail(Number(userId))
    .then((res) => {
      form.value = res;
      form.value.address_detail = `${res.lon},${res.lat},${res.address_detail}`;
    })
    .finally(() => {
      loading.value = false;
    });
}

/**
 * @description 提交按钮
 */
const handleSubmit = (form: any, done: Function) => {
  UserAPI.edit(form)
    .then(() => {
      ElMessage.success("保存成功");
      // 返回到列表页面
      router.back();
    })
    .finally(() => {
      done();
    });
};
</script>

<style lang="scss" scoped></style>
